package com.ants.modules.ArticleManage;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import com.ants.common.constant.CacheConstant;
import com.ants.common.system.api.ISysBaseAPI;
import com.ants.common.system.vo.LoginUser;
import com.ants.modules.ArticleManage.dto.ArticleManageDto;
import com.ants.modules.ArticleManage.dto.SysUserVo;
import com.ants.modules.ArticleManage.service.ArticleLikeCollectionService;
import com.ants.modules.ArticleManage.service.ArticleManageService;
import com.ants.modules.articleFavorites.service.ArticleFavoritesSubService;
import com.ants.modules.articleFollow.service.ArticleFollowService;
import com.ants.modules.articleLable.entity.ArticleLable;
import com.ants.modules.articleLable.service.ArticleLableService;
import com.ants.modules.articleSort.entity.ArticleSort;
import com.ants.modules.articleSort.service.ArticleSortService;
import com.ants.modules.utils.ElasticSearchUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO     启动时初始化 es
 * Author Chen
 * Date   2024/7/5 14:34
 */
@Slf4j
@Component
public class ArticleGenUtil implements ApplicationRunner {


    @Autowired
    ArticleManageService articleManageService;
    @Autowired
    ArticleLableService articleLableService;
    @Autowired
    ArticleSortService articleSortService;
    @Autowired
    ElasticsearchClient restHighLevelClient;
    @Autowired
    ElasticSearchUtils elasticSearchUtils;
    @Autowired
    ArticleLikeCollectionService articleLikeCollectionService;
    @Autowired
    ISysBaseAPI sysBaseAPI;
    @Autowired
    ArticleFavoritesSubService articleFavoritesSubService;
    @Autowired
    ArticleFollowService articleFollowService;

    @Override
    public void run(ApplicationArguments args) {
        List<ArticleManageDto> list = articleManageService.getAllList();

        for (ArticleManageDto entity : list) {
            genArticleManageDto(entity);
        }

        pushEs(list);
        log.info("初始化 《es》完毕, 共" + list.size() + "条！");
    }


    /**
     * 批量添加
     *
     * @param list
     */
    void pushEs(List<ArticleManageDto> list) {
        if (!elasticSearchUtils.existsIndex(CacheConstant.ES_INDEX)) {
            elasticSearchUtils.createIndex(CacheConstant.ES_INDEX);
        }


        List<BulkOperation> bulkOperationArrayList = new ArrayList<>();
        //遍历添加到bulk中
        for (ArticleManageDto articleManage : list) {
            bulkOperationArrayList.add(
                    new BulkOperation.Builder().create(builder -> builder.index(CacheConstant.ES_INDEX).id(articleManage.getId()).document(articleManage)).build()
            );
        }

        try {
            BulkResponse response = restHighLevelClient.bulk(builder -> builder.index(CacheConstant.ES_INDEX).operations(bulkOperationArrayList));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void genArticleManageDto(ArticleManageDto articleManage) {
        String id = articleManage.getId();
        // 获取分类
        ArticleSort articleSort = articleSortService.getById(articleManage.getArticleSort());
        articleManage.setArticleSort_dictText(articleSort.getName());
        articleManage.setSort(articleSort);
        // 获取标签
        String[] lables = articleManage.getArticleLable().split(",");
        List<ArticleLable> articleLableList = articleLableService.listByIds(Arrays.asList(lables));
        articleManage.setTags(articleLableList);
        List<String> lableNames = articleLableList.stream().map(ArticleLable::getName).collect(Collectors.toList());
        articleManage.setArticleLable_dictText(StringUtils.join(lableNames, ","));
        // 获取用户
        String username = articleManage.getCreateBy();
        LoginUser user = sysBaseAPI.getUserByName(username);
        SysUserVo userVo = new SysUserVo();
        BeanUtils.copyProperties(user, userVo);
        articleManage.setUser(userVo);

        // 获取文章点赞用户
        List<Map<String, String>> like_list = articleLikeCollectionService.getWxArticleLikeUser(id);
        articleManage.setLikeList(like_list);

    }

}
